package com.sky.controller.user;

import com.sky.constant.JwtClaimConstant;
import com.sky.controller.BaseController;
import com.sky.dto.UserLoginDTO;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtils;
import com.sky.vo.UserLoginVO;
import com.sky.vo.UserVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@Slf4j
@RequestMapping("/user/user")
@Api(tags = "用户相关接口")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userDTO) {
        log.info("微信用户登录：{}", userDTO);

        UserVO userVO = userService.wxLogin(userDTO);

        log.info("登录成功 =>{}", userVO);

        HashMap<String, Object> map = new HashMap<>();
        map.put(JwtClaimConstant.USER_ID, userVO.getId());
        String token = JwtUtils.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);

        UserLoginVO userLoginVO = UserLoginVO.builder().id(userVO.getId()).openid(userVO.getOpenId()).token(token).build();

        return Result.success(userLoginVO);
    }

}
